<template>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <h2 class="login-title">邮箱验证码登录</h2>
                <p class="login-subtitle">使用邮箱验证码快速登录</p>
            </div>

            <el-form :model="loginForm" 
                     :rules="loginRules" 
                     ref="loginFormRef"
                     class="login-form"
                     @submit.prevent="handleLogin">
                
                <el-form-item prop="email">
                    <el-input v-model="loginForm.email"
                              placeholder="请输入邮箱"
                              size="large"
                              prefix-icon="Message"
                              @keyup.enter="handleLogin" />
                </el-form-item>

                <el-form-item prop="code">
                    <div class="code-input-group">
                        <el-input v-model="loginForm.code"
                                  placeholder="请输入验证码"
                                  size="large"
                                  prefix-icon="Key"
                                  maxlength="6"
                                  @keyup.enter="handleLogin" />
                        <el-button type="primary" 
                                   size="large"
                                   :disabled="!loginForm.email || sendingCode || countdown > 0"
                                   :loading="sendingCode"
                                   @click="sendVerificationCode"
                                   class="send-code-btn">
                            {{ getCodeButtonText }}
                        </el-button>
                    </div>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" 
                               size="large"
                               :loading="logging"
                               @click="handleLogin"
                               class="login-btn">
                        {{ logging ? '登录中...' : '登录' }}
                    </el-button>
                </el-form-item>

                <div class="login-footer">
                    <el-button type="text" @click="goToPasswordLogin">
                        使用用户名密码登录
                    </el-button>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { emailLogin, sendEmailCode } from '@/api/admin/userprofile'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 表单数据
const loginForm = reactive({
    email: '',
    code: ''
})

// 表单引用
const loginFormRef = ref()

// 状态
const logging = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
let countdownTimer = null

// 表单验证规则
const loginRules = {
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { min: 4, max: 6, message: '验证码长度应在4-6位之间', trigger: 'blur' }
    ]
}

// 验证码按钮文本
const getCodeButtonText = computed(() => {
    if (sendingCode.value) {
        return '发送中...'
    }
    if (countdown.value > 0) {
        return `${countdown.value}s`
    }
    return '获取验证码'
})

// 发送验证码
const sendVerificationCode = async () => {
    if (!loginForm.email) {
        ElMessage.error('请先输入邮箱')
        return
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(loginForm.email)) {
        ElMessage.error('请输入正确的邮箱格式')
        return
    }

    try {
        sendingCode.value = true
        const res = await sendEmailCode({
            email: loginForm.email,
            type: 1 // 登录验证码
        })

        if (res.success) {
            ElMessage.success('验证码发送成功，请查收邮件')
            startCountdown()
        } else {
            ElMessage.error(res.message || '验证码发送失败')
        }
    } catch (error) {
        console.error('发送验证码失败:', error)
        ElMessage.error('验证码发送失败')
    } finally {
        sendingCode.value = false
    }
}

// 开始倒计时
const startCountdown = () => {
    countdown.value = 60
    countdownTimer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
            clearInterval(countdownTimer)
            countdownTimer = null
        }
    }, 1000)
}

// 处理登录
const handleLogin = async () => {
    if (!loginFormRef.value) return

    try {
        await loginFormRef.value.validate()
        logging.value = true

        const res = await emailLogin(loginForm)
        if (res.success) {
            // 保存token
            localStorage.setItem('token', res.data)
            
            // 获取用户信息
            await userStore.setUserInfoSmart()
            
            ElMessage.success('登录成功')
            router.push('/admin/index')
        } else {
            ElMessage.error(res.message || '登录失败')
        }
    } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error('登录失败')
    } finally {
        logging.value = false
    }
}

// 跳转到密码登录
const goToPasswordLogin = () => {
    router.push('/login')
}

// 组件卸载时清理定时器
onUnmounted(() => {
    if (countdownTimer) {
        clearInterval(countdownTimer)
    }
})
</script>

<style scoped>
.login-container {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20px;
}

.login-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    padding: 40px;
    width: 100%;
    max-width: 400px;
}

.login-header {
    text-align: center;
    margin-bottom: 32px;
}

.login-title {
    font-size: 28px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
}

.login-subtitle {
    font-size: 14px;
    color: #909399;
    margin: 0;
}

.login-form {
    width: 100%;
}

.code-input-group {
    display: flex;
    gap: 12px;
}

.code-input-group .el-input {
    flex: 1;
}

.send-code-btn {
    min-width: 120px;
    white-space: nowrap;
}

.login-btn {
    width: 100%;
    height: 44px;
    font-size: 16px;
    font-weight: 500;
}

.login-footer {
    text-align: center;
    margin-top: 20px;
}

.login-footer .el-button--text {
    color: #409EFF;
    font-size: 14px;
}

.login-footer .el-button--text:hover {
    color: #66b1ff;
}

/* 响应式设计 */
@media (max-width: 480px) {
    .login-card {
        padding: 24px;
        margin: 0 16px;
    }
    
    .login-title {
        font-size: 24px;
    }
    
    .code-input-group {
        flex-direction: column;
    }
    
    .send-code-btn {
        min-width: auto;
    }
}
</style>
